﻿using WebApp.BLL;
using WebApp.Web.Core.Auth;
using WebApp.BLL.Manage;
using WebApp.Common.EFQuery;
using WebApp.DAL;
using WebApp.Models;
using WebApp.ViewModels;
using WebApp.ViewModels.Manage;
using StackExchange.Profiling;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using WebApp.Common;
using WebApp.Common.Caching;
using WebApp.Web.Core;
using System.IO;
using Newtonsoft.Json.Linq;

namespace kzjd.rycp.WebApp.Controllers
{
    public class HomeController : Controller
    {
        private static readonly log4net.ILog log = log4net.LogManager.GetLogger("WebApp.Log");

        #region Index

        //[IgnoreAuthorizeFilter]
        public ActionResult Index()
        {
            return Redirect("~/eval/index");
            //return RedirectToAction("Index", "Eval");
            //DateTime from = Convert.ToDateTime(DateTime.Now.ToString("yyyy-MM-01"));
            //DateTime to = from.AddMonths(1).AddDays(-1);

            ////教学样品申请（待审批数量）
            //ViewBag.TeachingApproveCount = new V_apply_teaching_partsService().GetApplyCountByStatus((int)enmApplyPartStatus.待审批, businessuserId);

            ////教学样品申请（本月新增数）
            //ViewBag.TeachingMonthCount = new V_apply_teaching_partsService().GetApplyCount(businessuserId, from, to);

            ////教学样品申请（总数）
            //ViewBag.TeachingCount = new V_apply_teaching_partsService().GetApplyCount(businessuserId);

            ////项目样品申请（待审批数量）
            //ViewBag.ProjectApproveCount = new V_apply_project_partsService().GetApplyCountByStatus((int)enmApplyPartStatus.待审批, businessuserId);

            ////项目样品申请（本月新增数）
            //ViewBag.ProjectMonthCount = new V_apply_project_partsService().GetApplyCount(businessuserId, from, to);

            ////项目样品申请（总数）
            //ViewBag.ProjectCount = new V_apply_project_partsService().GetApplyCount(businessuserId);

            //return View();
        }

        #endregion

        #region 清除所有缓存

        [IgnoreAuthorizeFilter]
        [Route("home/clearcache")]
        public ActionResult ClearCache()
        {
            new MemoryCacheManager().Clear();

            return Json("缓存已清除！", JsonRequestBehavior.AllowGet);
        }

        #endregion
        
        #region 下载附件
        /// <summary>
        /// 下载附件
        /// </summary>
        /// <param name="id">步骤ID</param>
        /// <returns></returns>
        [IgnoreAuthorizeFilter]
        public ActionResult DownloadFile(string fileurl)
        {
            try
            {
                //string FileUploadRoot = new S_environmentService().GetValue("FileUploadRoot");
                string filepath = "G:\\" + fileurl.Replace('/', '\\');
                FileInfo fi = new FileInfo(filepath);
                if (System.IO.File.Exists(filepath))
                {
                    FileStream fileStream = new FileStream(filepath, FileMode.Open);

                    //byte[] buffer = new byte[fileStream.Length];
                    //try
                    //{
                    //    fileStream.Read(buffer, 0, buffer.Length);
                    //    fileStream.Seek(0, SeekOrigin.Begin);
                    //}
                    //finally
                    //{
                    //    if (fileStream != null)
                    //        fileStream.Close();
                    //}
                    Response.Headers["Content-Disposition"] = "inline;filename=\"" + HttpUtility.UrlDecode(fi.Name) + "\";";
                    //Response.AddHeader("Content-Disposition", "inline;filename=" + HttpUtility.UrlDecode(fi.Name));
                    //Response.ContentType = "application/pdf";
                    //response.addHeader("Content-Disposition", "inline;filename=\"a.jpg\"");
                    
                    return File(fileStream, "application/pdf");
                }
            }
            catch (Exception ex)
            {
                log.Error(ex);
            }
            return null;
        }


        #endregion


        public ActionResult ViewLog()
        {
            return View("Log");
        }

        public ActionResult About()
        {
            ViewBag.Message = "Your application description page.";

            return View();
        }

        public ActionResult Contact()
        {
            ViewBag.Message = "Your contact page.";

            return View();
        }

        public ActionResult Login()
        {
            return View();
        }

        public ActionResult Logout()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("Index", "Login");
        }

        [IgnoreAuthorizeFilter]
        public string Sql()
        {
            //if (!"admin".Equals(SessionManage.User.Username, StringComparison.OrdinalIgnoreCase))
            //{
            //    return "";
            //}

            if (!UserCache.IsSuperAdmin(SessionManage.User))
            {
                return "";
            }

            string includeid = Request.QueryString["id"];

            string table = Request.QueryString["t"];

            string sql = "";

            sql += "--TRUNCATE TABLE [" + table + "]\r\n\r\n";
            sql += "--DELETE FROM [" + table + "]\r\n\r\n";

            if (table.ToLower() == "s_menu")
            {
                var list = new S_menuService().List().OrderBy(p => p.Orderseq);
                foreach (var item in list)
                {
                    sql += this.GetSql(item, includeid) + "\r\n\r\n";
                }
            }
            else if (table.ToLower() == "s_role")
            {
                var list = new S_roleService().List().OrderBy(p => p.Roleid);
                foreach (var item in list)
                {
                    sql += this.GetSql(item, includeid) + "\r\n\r\n";
                }
            }
            else if (table.ToLower() == "s_role_menu")
            {
                var list = new S_role_menuService().List().OrderBy(p => p.Roleid);
                foreach (var item in list)
                {
                    sql += this.GetSql(item, includeid) + "\r\n\r\n";
                }
            }
            else if (table.ToLower() == "s_user_role")
            {
                var list = new S_user_roleService().List().OrderBy(p => p.User_id);
                foreach (var item in list)
                {
                    sql += this.GetSql(item, includeid) + "\r\n\r\n";
                }
            }
            else if (table.ToLower() == "s_lang_res")
            {
                //var list = new S_lang_resService().List().OrderBy(p => p.Rescategory).ThenBy(p => p.Lang).ThenBy(p => p.Reskey);
                var list = new S_lang_resService().List().OrderBy(p => p.Createtime).ThenBy(p => p.Lang).ThenBy(p => p.Reskey);
                foreach (var item in list)
                {
                    sql += this.GetSql(item, includeid) + "\r\n\r\n";
                }
            }
            else if (table.ToLower() == "s_gridcolumn")
            {
                var list = new S_gridcolumnService().List().Where(p => p.Userid == 0).OrderBy(p => p.Pagekey).ThenBy(p => p.Sort);
                foreach (var item in list)
                {
                    sql += this.GetSql(item, includeid) + "\r\n\r\n";
                }
            }
            else if (table.ToLower() == "s_dict")
            {
                var list = new S_dictService().List().OrderBy(p => p.Typecode).ThenBy(p => p.Sort);
                foreach (var item in list)
                {
                    sql += this.GetSql(item, includeid) + "\r\n\r\n";
                }
            }
            else if (table.ToLower() == "s_dicttype")
            {
                var list = new S_dicttypeService().List().OrderBy(p => p.Sort);
                foreach (var item in list)
                {
                    sql += this.GetSql(item, includeid) + "\r\n\r\n";
                }
            }
            else if (table.ToLower() == "s_environment")
            {
                var list = new S_environmentService().List().OrderBy(p => p.Id);
                foreach (var item in list)
                {
                    sql += this.GetSql(item, includeid) + "\r\n\r\n";
                }
            }

            if ("0".Equals(includeid))
            {
                ;
            }
            else
            {
                sql = "SET IDENTITY_INSERT " + table + " ON \r\n\r\n"
                    + sql + "\r\n\r\n"
                    + "SET IDENTITY_INSERT " + table + " OFF"; ;
            }

            return sql;
        }

        private string GetSql(object t, string includeid)
        {
            System.Reflection.PropertyInfo[] props = t.GetType().GetProperties();

            string fields = "";
            string values = "";

            foreach (System.Reflection.PropertyInfo p in props)
            {
                if ("0".Equals(includeid) && "id".Equals(p.Name, StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                fields += "[" + p.Name + "],";

                object val = p.GetGetMethod().Invoke(t, null);
                if (val == null)
                {
                    values += "null,";
                }
                else if (val.GetType() == typeof(int))
                {
                    values += val.ToString() + ",";
                }
                else if (val.GetType() == typeof(decimal))
                {
                    values += val.ToString() + ",";
                }
                else if (val.GetType() == typeof(DateTime))
                {
                    values += "'" + Convert.ToDateTime(val).ToString("yyyy-MM-dd HH:mm:ss.fff") + "',";
                }
                else
                {
                    values += "'" + val.ToString().Trim() + "',";
                }
            }

            return "INSERT INTO [" + t.GetType().Name + "] (" + fields.TrimEnd(',') + ")" + "\nVALUES (" + values.TrimEnd(',') + ")";
        }
    }
}